package cn.tedu.sp02.controller;

import cn.tedu.sp01.pojo.Item;
import cn.tedu.sp01.service.ItemService;
import cn.tedu.web.util.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Random;

@Slf4j
@RestController
public class ItemController {


    @Autowired
    private ItemService itemService;

    @Value("${server.port}")
    private int port;

    @GetMapping("/{orderId}")

    /*@RequestMapping对getpost都有效
    上述代码等效于
    @RequestMapping(path = "",method = RequestMethod.GET)*/
    public JsonResult<List<Item>> getItems(@PathVariable String orderId) throws InterruptedException {
        log.info("获取订单的商品列表, orderId=" + orderId);


        ///--设置随机延迟
        if (Math.random() < 0.9) {
            long t = new Random().nextInt(5000);
            log.info("item-service-" + port + " - 暂停 " + t);
            Thread.sleep(t);
        }

        List<Item> items = itemService.getItems(orderId);
        return JsonResult.ok(items).msg("port=" + port).data(items);
    }


    @PostMapping("/decreaseNumber")
    /*@RequestMapping对getpost都有效
    上述代码等效于
    @RequestMapping(path = "",method = RequestMethod.POST)*/

    /*@RequestBody*/
    public JsonResult<?> decreaseNumber(@RequestBody List<Item> items) {

        itemService.decreaseNumber(items);
        return JsonResult.ok().msg("减少库存成功");
    }


}
